<template>
   <div class="addBrand-container">
    <div class="container">
        <el-form ref="form"  :rules="rules"  :model="form" label-width="80px">
        <el-form-item label="姓名" prop="username">
          <el-input style="width: 20%;" placeholder="请输入姓名" v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="form.sex" placeholder="请选择性别">
            <el-option label="男" value="男"></el-option>   
            <el-option label="女" value="女"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="权限">
          <el-select v-model="value" multiple placeholder="请选择权限">
            <el-option
              v-for="item in menu"
              :key="item.id"
              :label="item.label"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item  label="头像" prop="image">
          <el-upload
            :limit="1"
            list-type="picture-card"
            class="avatar-uploader"
            action="/api/api/common/upload"
            :on-success="handleAvatarSuccess"
            :show-file-list="true"
            :headers="{token:token}"
            >
            <img v-if="form.image" :src="form.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="电话号码" prop="phone">
          <el-input style="width: 20%;" placeholder="请输入电话号码" v-model="form.phone"></el-input>
        </el-form-item>
        <div class="subBox">
          <el-button type="primary" @click="submitForm('form',false)">保存</el-button>
          <el-button 
            v-if="this.optType === 'add'" 
            type="primary" 
            @click="submitForm('form',true)">保存并继续添加用户
          </el-button>
          <el-button @click="() => this.$router.push('/layout/user')">返回</el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script>
import {selectUserById,updateUserById,addUser,selectMenu} from '@/api/login-register'
import Cookies from 'js-cookie';
export default {
  name: 'AddUser',

  data() {
    return {
      optType: '',//当前操作的类型，新增或者修改
      token:Cookies.get('token'),
      form:{
        username:'',
        sex:'',
        image:'',
        phone:'',
        ids:''
      },
      menu:[],
      value:'',
      rules:{
        username:[
          {required:true,message:'请输入姓名'}
        ],
        phone: [
          { required: true, trigger: 'blur',validator: (rule,value,callback) => {
              if(value === '' || (!/^1(3|4|5|6|7|8|9)\d{9}$/.test(value))){
                callback(new Error('请输入正确的手机号！'))
              }else{
                callback()
              }
            } 
          }
        ],
        sex:[
          {required:true,message:'请输入性别'}
        ],
        image:[
          {required:true,message:'请选择图片'}
        ]
      },
    };
  },

  mounted() {
    
  },
  created() {
    //获取路由参数（id），如果有则为修改操作，否则为新增操作
    this.optType = this.$route.query.id ? 'update' : 'add'
    if(this.optType === 'update') {
      //修改操作，需要根据id查询员工信息用于页面回显
      selectUserById(this.$route.query.id).then(res => {
        if(res.data.code === 200){
          console.log("修改用户",res.data)
          this.form = res.data.data
        }
      })
    }
    // 查询权限信息，在页面回显
    selectMenu().then(res => {
        if(res.data.code === 200){
          console.log("查询权限",res.data)
          this.menu = res.data.data
        }
      })
  },
  methods: {
    submitForm(formName,isContinue){
      //进行表单校验
      this.$refs[formName].validate((valid) => {
        if(valid) {
          //表单校验通过，发起Ajax请求，将数据提交到后端
          if(this.optType === 'add'){//新增操作
            this.form.ids = this.value
            console.log('权限~~~~', this.form)
            addUser(this.form).then((res) => {
                if(res.data.code === 200){
                  this.$message.success('用户添加成功！')
                  if(isContinue){
                  this.form = {
                      username:'',
                      password:'',
                      sex: '男',
                      image:'',
                      phone:''
                    }
                  }else {
                    this.$router.push('/layout/user')
                  }
                }else {
                  this.$message.error(res.data.msg)
                }
              })
          }else{//修改操作
            updateUserById(this.form).then(res => {
              if(res.data.code === 200){
                this.$message.success('用户信息修改成功！')
                this.$router.push('/layout/user')
              }
            })
          }
        }
      })
    },
    handleAvatarSuccess(res,file){
      // 图片上传成功修改头像
      this.form.image = res.data
    }
  },
};
</script>


<style lang="less" scoped>
.avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
.addBrand {
  &-container {
    margin: 30px;
    margin-top: 30px;
    .HeadLable {
      background-color: transparent;
      margin-bottom: 0px;
      padding-left: 0px;
    }
    .container {
      position: relative;
      z-index: 1;
      background: #fff;
      padding: 30px;
      border-radius: 4px;
      // min-height: 500px;
      .subBox {
        padding-top: 30px;
        text-align: center;
        border-top: solid 1px #c3c8ce;
      }
    }
    .idNumber {
      margin-bottom: 39px;
    }

    .el-form-item {
      margin-bottom: 29px;
    }
    .el-input {
      width: 293px;
    }
  }
}
</style>